import { createRouter, createWebHashHistory } from "vue-router";
import { setBrowserTitle, getMenuList, hasMenuPermission } from "./tools/tools";

import NProgress from "nprogress"; // 引入 nprogress
import "nprogress/nprogress.css"; // 引入 nprogress 的样式

// 界面路由
import layoutRoutes from "./layouts";

import { getCookie } from "@/utils/cookie";

const router = createRouter({
  history: createWebHashHistory(),
  // 加载所有路由
  routes: layoutRoutes,
});

router.beforeEach(async (to, _from, next) => {
  // 开始进度条
  NProgress.start();

  // 设置对应路由的浏览器标签标题
  setBrowserTitle(to)

  const token = getCookie("token")

  if (['Root', 'Login', 'Logout', 'NoPermission', 'Base', '404'].includes(to.name as string)) {
    // 跳转登录页面时，不执行其他逻辑
    next()
  } else if (!token) {
    // 跳转页面且无登录权限时跳转到登录页面
    next({
      path: '/login',
      replace: true,
    })
  } else if (!hasMenuPermission(to)) {
    console.log(to.name)
    // 没有菜单权限时，跳转无权限页面
    next({
      name: 'NoPermission',
      replace: true
    })
  } else {
    // 获取菜单
    await getMenuList(to);

    next()
  }
});

// 路由变化完成时停止进度条
router.afterEach(() => {
  NProgress.done(); // 完成进度条
});

export default router;
